package com.mind.customer.utils.datasource;

import com.alibaba.fastjson2.JSONArray;
import com.mind.system.domain.AjDatasource;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.HashMap;
import java.util.Map;
@Component
public class ReflectionDao {


    public JSONArray queryAll(AjDatasource datasource) {
        JSONArray list = new JSONArray();
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection(datasource);
            String sql = "SELECT * FROM " + datasource.getParams() + ";";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            while (rs.next()) {
                Map<String, Object> rowMap = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {
                    String columnName = metaData.getColumnName(i);
                    Object columnValue = rs.getObject(i);
                    rowMap.put(columnName, columnValue);
                }
                list.add(rowMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(rs, pstmt, conn);
        }

        return list;
    }

    public <T> T queryById(Class<T> clazz, AjDatasource datasource, int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        T entity = null;

        try {
            conn = JdbcUtils.getConnection(datasource);
            String sql = "SELECT * FROM users WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                entity = clazz.getDeclaredConstructor().newInstance(); // 创建实体类的实例
                Field[] fields = clazz.getDeclaredFields(); // 获取所有字段

                for (Field field : fields) {
                    field.setAccessible(true); // 确保私有属性也可以访问
                    String columnName = field.getName(); // 假设数据库列名与字段名相同
                    Object value = rs.getObject(columnName);
                    field.set(entity, value); // 使用反射设置属性值
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(rs, pstmt, conn);
        }

        return entity;
    }
}
